package gui.dialog;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Window;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;

import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLEditorKit;

import utils.Configuration;
import utils.Utils;

public class ChatAproposDialog extends ChatDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/* Information about the window... */
	private static final String APROPOS_TITLE = "Apropos" ;
	private static Dimension APROPOS_SIZE = new Dimension(300, 200) ;
	
	/* Some file informations... */
	private static final String APROPOS_IMG_FOLDER = "apropos" ;
	private static final String APROPOS_FILE = "apropos.html" ;
	private static final String APROPOS_CSS = "apropos.css" ;
	
	/* Pattern to replace img src attribute in content... */
	private static final String IMG_PATTERN = "<img(.*)src=\"([^\"]+)\"(.*)/>" ;
	private static final String IMG_REPLACER = "<img$1src=\"file:" + Configuration.getImageFolder() + "/" + 
			APROPOS_IMG_FOLDER + "/" + "$2\" $3 />" ;
	
	private static String changeIMGFolder (String content) {
		return Pattern.compile(IMG_PATTERN).matcher(content).replaceAll(IMG_REPLACER) ;
	}
		
	public ChatAproposDialog (Window master) {
		super (master, APROPOS_TITLE, APROPOS_SIZE) ;
		/* Get the content and modify it : */
		String content = "";
		try {
			content = new Scanner(new File(Configuration.getRessourceFolder() + File.separator + APROPOS_FILE), "UTF-8").useDelimiter("\\A").next();
		} 
		catch (FileNotFoundException e) {
			
		}
		content = changeIMGFolder(content) ;
		JEditorPane contentArea = new JEditorPane("text/html", content) ;
		contentArea.setEditable(false) ;
		contentArea.setOpaque(false) ;
		File cssFile = new File(Configuration.getRessourceFolder() + File.separator + APROPOS_CSS) ;
		if (cssFile.exists() && cssFile.canRead()) {
			String cssContent = "";
			try {
				cssContent = new Scanner(cssFile).useDelimiter("\\A").next();
				((HTMLEditorKit)contentArea.getEditorKit()).getStyleSheet().addRule(cssContent) ;
			}
			catch (Exception e) {

			}
		}
		/* Create HyperLinkListener on content area */
		contentArea.addHyperlinkListener(new HyperlinkListener() {
			@Override
			public void hyperlinkUpdate(HyperlinkEvent hle) {
				if (HyperlinkEvent.EventType.ACTIVATED.equals(hle.getEventType())) {  
					Utils.openURL(hle.getDescription()) ;
				}  
			}
		}) ;
		/* Add to the dialog and configure the dialog... */
		add(new JScrollPane(contentArea), BorderLayout.CENTER) ;
	}

}
